import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Message} from '../../../../../ng-tools/src/message/message';
import {Subscription, timer} from 'rxjs';
import {DvbConfigService} from '../../../../services/api/dvb-config.service';
import {BadgePipe, LoadingComponent, MessageService, ModalComponent, paginationFactory, PaginationService, ProgressBarService, Table, UnitPipe} from '../../../../../ng-tools';
import {HttpClient} from '@angular/common/http';
import {DvbConfigFormatterService} from '../../../../services/formatter/dvb-config-formatter.service';
import {finalize} from 'rxjs/internal/operators';
import {DvbChannelInfoComponent} from './dvb-channel-info/dvb-channel-info.component';
import {DvbChannelRunningInfoComponent} from './dvb-channel-running-info/dvb-channel-running-info.component';
import {SimpleJsonFormatter} from '../../../../../ng-tools';

const dvbConfigChannelPaginationProvider = {
  provide: PaginationService,
  useFactory: paginationFactory,
  deps: [HttpClient, DvbConfigService],
};
@Component({
  selector: 'dvb-channel-manager',
  templateUrl: './dvb-channel-manager.component.html',
  styleUrls: ['./dvb-channel-manager.component.scss'],
  providers: [
    UnitPipe,
    BadgePipe,
    dvbConfigChannelPaginationProvider,
    DvbConfigService,
    DvbConfigFormatterService
  ]
})
export class DvbChannelManagerComponent implements OnInit, AfterViewInit, OnDestroy, Message {
  subscriptions: Subscription;
  @ViewChild(LoadingComponent) loading: LoadingComponent;
  @ViewChild('modal') private modal: ModalComponent;
  dvbConfigPage;
  runningTimeInfos = [];
  runningChannels = [];
  loadingOptions = {
    id: 'dvbChannelManagerLoadingModal',
    message: '',
    textColor: 'teal'
  };
  breadcrumb = [
    {name: '通道管理', cssIcon: 'fa fa-fw fa-task'},
    {name: '设备信息', cssIcon: 'fa fa-fw fa-task'}
  ];
  dvbConfiglTable = new Table({
    headers: this.dvbFormatterService.timeFormatter,
    buttons: [
      {
        btnClass: 'btn btn-danger btn-sm mr-1 px-1 py-0',
        iconClass: 'fa fa-fw fa-play-circle',
        isShow: true,
        click: (e) => {
          if (e.status === 2) {
            alert('当前通道在运行状态');
          } else {
            this.loading.show('正在开启该通道!');
          this.configService.post(this.configService.urls.run_and_stop_channel_status, {'channel_id': e.id, 'op': 1}).subscribe((resp) => {
            this.runningChannels.push({'channel_id': e.id, 'pid': resp.body.pid});
            this.loading.show('通道开启成功!', 'success');
            timer(1000).subscribe(() => {
              this.loading.hide();
              this.refresh();
            });
          }, (error) => {
            console.log(error.error);
            this.loading.show('通道开启失败!', 'danger');
            timer(1000).subscribe(() => {
              this.loading.hide();
              const errorInfo = error.error;
              let alertInfo = '';
              if (errorInfo.hasOwnProperty('result')) {
                alertInfo = errorInfo.result;
              } else {
                alertInfo = errorInfo.msg;
              }
              alert(alertInfo);
            });
          });
          }
        }
      },
      {
        btnClass: 'btn btn-danger btn-sm mr-1 px-1 py-0',
        iconClass: 'fa fa-fw fa-stop-circle-o',
        isShow: true,
        click: (e) => {
          let pid = 0;
          if (e.status === 1) {
            alert('当前通道是停止状态');
          } else {
            for (const channel of this.runningChannels) {
              if (e.id === channel.channel_id) {
                pid = channel.pid;
              }
            }
            this.loading.show('正在停止该通道!');
            this.configService.post(this.configService.urls.run_and_stop_channel_status, {'op': 2, 'pid': pid, 'channel_id': e.id}).subscribe((resp) => {
              this.loading.show('通道停止成功!', 'success');
              timer(1000).subscribe(() => {
                this.loading.hide();
                this.refresh();
              });
            }, (error) => {
              console.log(error);
              this.loading.show('通道停止失败!', 'danger');
              timer(1000).subscribe(() => {
                this.loading.hide();
                alert(error.body.result);
              });
            });
          }
        }
      },
      {
        btnClass: 'btn btn-danger btn-sm mr-1 px-1 py-0',
        iconClass: 'fa fa-fw fa-info-circle font-75',
        isShow: true,
        click: (e) => {
          if (e.status === 1) {
            this.showDvbChannelInfo(e);
          } else {
            this.configService.post(this.configService.urls.get_running_channel_info, {'id': e.id}).subscribe((resp) => {
              this.showDvbChannelRunningInfo(resp.body);
            });
          }
        }
      }
    ],
  });
  constructor(private configService: DvbConfigService,
              private message: MessageService,
              private http: HttpClient,
              private pagination: PaginationService,
              private dvbFormatterService: DvbConfigFormatterService,
              public progress: ProgressBarService) { }

  ngOnInit() {
    this.configService.get(this.configService.urls.get_running_channels).subscribe((res) => {
      this.runningChannels = res.body;
    });
    this.configService.get(this.configService.urls.get_channels_running_time).subscribe((res) => {
      this.runningTimeInfos = res.body;
    });
    this.pagination.setPageParam(1, 12);
    this.pagination.queryParams = [{key: 'status', value: 2, op: 'a'}, {key: 'status', value: 1, op: 'a'}];
    this.pagination.init(this.dvbConfiglTable.options.headers);
    this.dvbConfigPage = this.pagination;
    /** 绑定事件 */
    this.pagination.dataLoadSubscriber$.pipe(finalize(() => {
      const formattered = this.pagination.page.formattedResults;
      for (const formatterItem of formattered) {
        for (const info of this.runningTimeInfos) {
          if (formatterItem.status === 2) {
            if (info.id === formatterItem.id) {
              formatterItem['time'] = info.time;
            }
          } else {
            formatterItem['time'] = '';
          }
        }
      }
      console.log(this.pagination.page.formattedResults);
      this.message.sendMessage('page load progress', this);
    })).subscribe({
      error: error => {
        console.log(error);
      }
    });
  }
  refresh() {
    this.configService.get(this.configService.urls.get_channels_running_time).subscribe((res) => {
      this.runningTimeInfos = res.body;
    });
    this.configService.get(this.configService.urls.get_running_channels).subscribe((res) => {
      this.runningChannels = res.body;
    });
    this.pagination.dataLoadSubscriber$.subscribe(() => {
      this.pagination.page.ready = false;
      this.configService.get('').subscribe((res: any) => {
        this.pagination.page.results = res.body;
        // this.pagination.page.count = res.body.count;
        // this.pagination.page.previous = res.body.previous;
        // this.pagination.page.next = res.body.next;
        this.pagination.page.current = res.url;
        if (this.pagination.simpleFormatter) {
          this.pagination.page.formattedResults = SimpleJsonFormatter.formatDataSet(this.pagination.simpleFormatter, this.pagination.page.results);
          const formattered = this.pagination.page.formattedResults;
          for (const formatterItem of formattered) {
            for (const info of this.runningTimeInfos) {
              if (formatterItem.status === 2) {
                if (info.id === formatterItem.id) {
                  formatterItem['time'] = info.time;
                }
              } else {
                formatterItem['time'] = '';
              }
            }
          }
          this.pagination.page.ready = true;
        }
        this.pagination.page.ready = true;
      }, (resp) => {
        this.pagination.page.ready = false;
        this.pagination.page.error = resp.error.msg;
      });
    });
  }
  showDvbChannelInfo(channel) {
    this.modal.show({
      title: '通道信息',
      cssIcon: 'fa fa-fw fa-plus-circle',
      dynamicComponent: {
        component: DvbChannelInfoComponent,
        data: channel,
        events: null,
      },
      data: null
    });
  }
  showDvbChannelRunningInfo(channel) {
    this.modal.show({
      title: '通道运行信息',
      cssIcon: 'fa fa-fw fa-plus-circle',
      size: 'lg',
      dynamicComponent: {
        component: DvbChannelRunningInfoComponent,
        data: channel,
        events: null,
      },
      data: null
    });
  }
  ngAfterViewInit(): void {
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
  }

  ngOnDestroy(): void {
  }

}
